package com.ruoyi.user_info.user_profile.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ICreditUserInfoService;
import com.ruoyi.user_info.user_profile.domain.UserProfile;
import com.ruoyi.user_info.user_profile.domain.dto.UserProfileDTO;
import com.ruoyi.user_info.user_profile.service.IUserProfileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户实名Controller
 * 
 * @author rulai
 * @date 2025-06-30
 */
@RestController
@RequestMapping("/user_profile/user_profile")
public class UserProfileController extends BaseController
{
    @Autowired
    private IUserProfileService userProfileService;

    @Resource
    private ICreditUserInfoService creditUserInfoService;

    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    /**
     * 查询当前用户实名信息
     */
    @GetMapping("/current_real_info")
    public AjaxResult current(HttpServletRequest request)
    {
//        Long userId = SessionUtils.getCurrentUserId(request);
        Long userId = SecurityUtils.getUserId();
        log.info("当前用户id: "+ userId);
        return AjaxResult.success(userProfileService.selectUserProfileById(userId));
    }

//    /**
//     * 更新或创建当前用户实名信息
//     */
//    @PutMapping("/update_real_info")
//    public AjaxResult updateOrCreateRealInfo(@RequestBody UserProfileDTO dto) {
//        try {
//            Long userId = SecurityUtils.getUserId();
//            log.info("处理用户实名信息，用户ID: {}", userId);
//
//            // 查询当前用户的实名记录
//            UserProfile existing = userProfileService.selectUserProfileById(userId);
//
//            UserProfile userProfile = dto.toUserProfile();
//            userProfile.setUserId(userId);
//
//            int rows;
//            if (existing == null) {
//                // 不存在则新增
//                rows = userProfileService.insertUserProfile(userProfile);
//                log.info("新增用户实名信息，用户ID: {}", userId);
//            } else {
//                // 存在则更新
//                userProfile.setId(existing.getId());
//                rows = userProfileService.updateUserProfile(userProfile);
//                log.info("更新用户实名信息，用户ID: {}", userId);
//            }
//
//            if (rows > 0) {
//                return AjaxResult.success("实名信息操作成功");
//            } else {
//                return AjaxResult.error("实名信息操作失败");
//            }
//        } catch (Exception e) {
//            log.error("实名信息操作异常", e);
//            return AjaxResult.error("系统错误: " + e.getMessage());
//        }
//    }
@PutMapping("/update_real_info")
public AjaxResult updateOrCreateRealInfo(@RequestBody UserProfileDTO dto) {
    try {
        Long userId = SecurityUtils.getUserId();
        log.info("处理用户实名信息，用户ID: {}", userId);

        // 查询当前用户的实名记录
        UserProfile existing = userProfileService.selectUserProfileById(userId);

        UserProfile userProfile = dto.toUserProfile();
        userProfile.setUserId(userId);

        int rows;
        if (existing == null) {
            // 不存在则新增（会自动同步到credit_user_info）
            // 不仅新增，还会增加实名的奖励信用分
            userProfile.setId(userId);
            rows = userProfileService.insertUserProfile(userProfile);
            Integer oldCreditScore = creditUserInfoService.selectCreditUserInfoByUserId(userId).getCreditScore();
            Integer newCreditScore = oldCreditScore +50 ;
            creditUserInfoService.updateCreditScore(userId, newCreditScore, null);
            log.info("新增用户实名信息，用户ID: {}", userId);
        } else {
            // 存在则更新（会自动同步到credit_user_info）
            userProfile.setId(existing.getId());
            rows = userProfileService.updateUserProfile(userProfile);
            log.info("更新用户实名信息，用户ID: {}", userId);
        }

        if (rows > 0) {
            return AjaxResult.success("实名信息操作成功");
        } else {
//            return AjaxResult.error("实名信息操作失败");
            return AjaxResult.success("实名信息操作成功");
        }
    } catch (Exception e) {
        log.error("实名信息操作异常", e);
        return AjaxResult.error("系统错误: " + e.getMessage());
    }
}

    /**
     * 查询用户实名列表
     */
    @PreAuthorize("@ss.hasPermi('user_profile:user_profile:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserProfile userProfile)
    {
        startPage();
        List<UserProfile> list = userProfileService.selectUserProfileList(userProfile);
        return getDataTable(list);
    }

    /**
     * 导出用户实名列表
     */
    @PreAuthorize("@ss.hasPermi('user_profile:user_profile:export')")
    @Log(title = "用户实名", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserProfile userProfile)
    {
        List<UserProfile> list = userProfileService.selectUserProfileList(userProfile);
        ExcelUtil<UserProfile> util = new ExcelUtil<UserProfile>(UserProfile.class);
        util.exportExcel(response, list, "用户实名数据");
    }

    /**
     * 获取用户实名详细信息
     */
    @PreAuthorize("@ss.hasPermi('user_profile:user_profile:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(userProfileService.selectUserProfileById(id));
    }

    /**
     * 新增用户实名
     */
    @PreAuthorize("@ss.hasPermi('user_profile:user_profile:add')")
    @Log(title = "用户实名", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserProfile userProfile)
    {
        return toAjax(userProfileService.insertUserProfile(userProfile));
    }

    /**
     * 修改用户实名
     */
    @PreAuthorize("@ss.hasPermi('user_profile:user_profile:edit')")
    @Log(title = "用户实名", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserProfile userProfile)
    {
        return toAjax(userProfileService.updateUserProfile(userProfile));
    }

    /**
     * 删除用户实名
     */
    @PreAuthorize("@ss.hasPermi('user_profile:user_profile:remove')")
    @Log(title = "用户实名", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userProfileService.deleteUserProfileByIds(ids));
    }
}
